import PropTypes from 'prop-types'
import React, { memo, useEffect, useState } from 'react'
import { Space, message, Button } from 'antd'
import {
    PauseCircleOutlined,
    PlayCircleOutlined,
    PoweroffOutlined,
    ExpandOutlined,
    PictureOutlined,
    ZoomInOutlined
} from '@ant-design/icons';

import { VideoWarpper } from './style'
const url = ""
let player = null
const index = memo((props) => {
    const { playUrl } = props
    const IS_MOVE_DEVICE = document.body.clientWidth < 992 // 是否移动设备
    const { height = "100%", playURL } = props
    const MSE_IS_SUPPORT = !!window.MediaSource // 是否支持mse
    const tabActive = MSE_IS_SUPPORT ? 'mse' : 'decoder'
    const [startPlayBtnState, setStartPlayBtnState] = useState(false)
    const [videoLoading, setVideoLoading] = useState(false)
    const [currentPlayIndex, setCurrentPlayIndex] = useState(0)

    /** 初始化播放器 */
    const initPlayer = () => {
        // setVideoLoading(true)
        player = new window.JSPlugin({
            szId: 'player-container',
            szBasePath: '/',
            iMaxSplit: 2,
            splitNum: IS_MOVE_DEVICE ? 1 : 2,
            iCurrentSplit: 1,
            openDebug: true,
            oStyle: {
                borderSelect: '#FFCC00',
            },
        })
        player.JS_ArrangeWindow(2).then(
            () => { console.log(`arrangeWindow to ${2}x${2} success`) },
            e => { console.error(e) }
        )
        player.JS_SetConnectTimeOut(currentPlayIndex, 6).then(
            () => {
                console.info('JS_SetConnectTimeOut success')
            },
            (err) => {
                console.info(`JS_SetConnectTimeOut failed:${err}`)
            },
        )
        // 事件回调绑定
        player.JS_SetWindowControlCallback({
            windowEventSelect(iWndIndex) {
                // 插件选中窗口回调
                console.log('windowSelect callback: ', iWndIndex)
                setCurrentPlayIndex(iWndIndex)
            },
            pluginErrorHandler(iWndIndex, iErrorCode, oError) {
                if (iErrorCode === '0x12f900009') {
                    message.error('取流超时错误')
                    setStartPlayBtnState(true)
                    setVideoLoading(false)
                }
                // 插件错误回调
                console.log('pluginError callback: ', iWndIndex, iErrorCode, oError)
                message.error(`pluginError：${iErrorCode}`)
            },
            windowEventOver(iWndIndex) {
                // 鼠标移过回调
                // console.log(iWndIndex)
            },
            windowEventOut(iWndIndex) {
                // 鼠标移出回调
                // console.log(iWndIndex)
            },
            windowEventUp(iWndIndex) {
                // 鼠标mouseup事件回调
                // console.log(iWndIndex);
            },
            windowFullCcreenChange(bFull) {
                // 全屏切换回调
                console.log('fullScreen callback: ', bFull)
            },
            firstFrameDisplay(iWndIndex, iWidth, iHeight) {
                // 首帧显示回调
                console.log('firstFrame loaded callback: ', iWndIndex, iWidth, iHeight)
                player.JS_Resize(352, 288)
            },
            performanceLack() {
                message.warning('性能不足')
                // 性能不足回调
                console.log('performanceLack callback: ')
            },
        })

        // 设置播放容器的宽高并监听窗口大小变化
        window.addEventListener('resize', () => {
            // player.JS_Resize()
        })
        realplay(playUrl)
    }

    /** 模式判断 */
    function mode() {
        // 解码类型：0=普通模式; 1=高级模式 默认为0
        return tabActive === 'mse' ? 0 : 1
    }

    /** 获取视频信息 */
    async function getVideoInfo() {
        try {
            const res = (await player.JS_GetVideoInfo(currentPlayIndex))
            return Promise.resolve(res)
        }
        catch (error) {
            return Promise.reject(error)
        }
    }

    /* 开始播放 */
    async function realplay(playURL) {
        if (!playURL) {
            return ''
        }
        await stopPlay()
        setVideoLoading(true)
        console.log(currentPlayIndex, '播放器下标',)
        player.JS_Play(playURL, { playURL, mode }, currentPlayIndex).then(
            () => {
                console.log('realplay success')
                setStartPlayBtnState(false)
                setVideoLoading(false)
            },
            (e) => {
                console.error(e)
            },
        )
    }
    /** 停止播放 */
    async function stopPlay() {
        try {
            const res = await player.JS_Stop(currentPlayIndex)
            return res
        } catch (error) {
            message.error(error || "系统出错")
        }
    }
    /**停止全部窗口播放 */
    async function stopAllPlay() {
        await player.JS_StopRealPlayAll()
    }

    /** 全屏操作 */
    function handleFullScreen() {
        player.JS_FullScreenSingle(currentPlayIndex).then(
            () => {
                console.info('JS_FullScreenSingle success')
            },
            (err) => {
                console.info('JS_FullScreenSingle failed', err)
            },
        )
    }

    /** 截图操作 */
    async function capturePicture() {
        const fileName = '截图'
        const fileType = 'JPEG'

        // 下载到本地
        player.JS_CapturePicture(currentPlayIndex, fileName, fileType).then(
            () => {
                console.info('JS_CapturePicture success')
            },
            (err) => {
                console.info(`JS_CapturePicture failed:${err}`)
            },
        )
    }

    /** 电子放大功能 */
    function enableZoom() {
        if (mode() === 0) {
            return message.warning('您的设备暂不支持电子放大功能')
        }
        player.JS_EnableZoom().then(
            () => {
                console.info('JS_EnableZoom success')
            },
            (err) => {
                console.info(`JS_EnableZoom failed:${err}`)
            },
        )
    }

    /**整体全屏 */
    function wholeFullScreen() {
        player.JS_FullScreenDisplay(true).then(
            () => { console.log(`wholeFullScreen success`) },
            e => { console.error(e) }
        )
    }

    /** 事件处理 */
    function iconClickhandle(val) {
        switch (val) {
            case 'play':
                realplay(playUrl)
                setStartPlayBtnState(false)
                break
            case 'stop':
                stopPlay()
                setStartPlayBtnState(true)
                break
            case 'fullscreen':
                handleFullScreen()
                break
            case 'capturePicture':
                capturePicture()
                break
            case 'enableZoom':
                enableZoom()
                break
            case 'allFullScreen':
                wholeFullScreen()
                break
            case 'stopAll':
                stopAllPlay()
                break
            default: {
                stopPlay()
            }
        }
    }
    useEffect(() => {
        initPlayer()
        return () => {
            console.log("销毁播放器")
            stopAllPlay()
            player = null
        }
    }, [])

    useEffect(() => {
        if (!player) {
            initPlayer()
            return
        }
        playUrl && realplay(playUrl)
    }, [playUrl])

    return (
        <VideoWarpper height={height}>
            <div className="player-wrapper" >
                <div id="player-container" className="player-box right" />
                {/* <div className="controls">
                    <Space>
                        <Button icon={<ExpandOutlined />} size="small" type='default' ghost={true} onClick={e => iconClickhandle('allFullScreen')}>整体全屏</Button>
                        <Button icon={<ExpandOutlined />} size="small" type='default' ghost={true} onClick={e => iconClickhandle('fullscreen')}>单窗口全屏</Button>
                        <Button icon={<PoweroffOutlined />} size="small" type='default' ghost={true} onClick={e => iconClickhandle("stopAll")}>全部停止</Button>
                        <Button icon={<PictureOutlined />} size="small" type='default' ghost={true} onClick={e => iconClickhandle('capturePicture')}>截取窗口图片</Button>
                    </Space>
                </div> */}
            </div>
        </VideoWarpper >
    )
})

index.propTypes = {
    height: PropTypes.number
}

export default index